﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Pomodoro.Core.Presenter;
using System.Text;
using System.Text.RegularExpressions;

namespace Pomodoro.Web.Views
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ClientTaskView : IHttpHandler
    {
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        private PomodoroPresenter presenter;
        
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";
            context.Response.ContentEncoding = Encoding.UTF8;
            this.GetResultMethod(context.Request.QueryString[0],context.Request.QueryString[1]);
        }

        private Dictionary<string,string> GetParameters(string stream) {
            Dictionary<string, string> p = new Dictionary<string, string>();
            Regex regex = new Regex("[a-z]+:[0-9]+");

            foreach (Match match in regex.Matches(stream))
                p.Add(match.Value.Substring(0, match.Value.IndexOf(':')), match.Value.Substring(match.Value.IndexOf(':')+1));
            return p;
        }

        private string GetResultMethod(string eventName,string paramsEvent){
            string notification = String.Empty;
            Dictionary<string,string> p = GetParameters(paramsEvent);
            switch (eventName) { 
                case "StartTask":
                    presenter = new PomodoroPresenter();
                    presenter.StartTask(Convert.ToInt32(p["id"]));
                    break;
                case "EndTask":
                    presenter = new PomodoroPresenter();
                    notification = presenter.EndTask(Convert.ToInt32(p["id"]));
                    break;

            }
            return notification;
        }
    }
}
